package teabag;

import java.util.ArrayList;

import org.w3c.dom.Node;

public class ActionManager {
	private static ActionManager instance;
	private ArrayList<Action> actionList;
	
	private ActionManager()
	{
		actionList = new ArrayList<Action>();
	}
	public String toString()
	{
		String text = "Actions:\n";
		for( Action a : actionList )
			text += a + " ";
		return text;
	}
	
	protected static ActionManager getInstance()
	{
		if( instance == null )
			instance = new ActionManager();
		return instance;
	}
	
	protected Action addAction( String name, Node doNode )
	{
		Action a = new Action( name, doNode );
		return ( actionList.add( a ) ? a : null );
	}
	protected void removeAction( Action a )
	{
		actionList.remove( a );
	}
	
	protected Node getCommandNode( String actionName )
	{
		Action a = findAction( actionName );
		return( a != null ? a.getDoNode() : null );
	}
	
	protected Action findAction( String name )
	{
		for( Action ax : actionList )
			if( ax.containsAlias(name) ) return ax;
		return null;
	}
	
	public class Action
	{
		private String name;
		private ArrayList<String> aliasList;
		private Node doNode;
		
		public Action( String sName, Node actionNode ){
			name = sName;
			aliasList = new ArrayList<String>();
			doNode = actionNode;
		}
		public String toString() 
		{
			String text = name + "(";
			for( String a : aliasList )
				text += a + ",";
			return text += ")"; 
		}
		public Node getDoNode()
		{
			return doNode;
		}
		public void addAlias( String alias )
		{
			aliasList.add( alias );
		}
		public boolean containsAlias( String alias )
		{
			if( name.equals( alias ) ) return true;
			for( String a : aliasList )
				if( a.equals(alias) ) return true;
			return false;
		}
	}
}
